<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>画板</title>
    <link rel="stylesheet" href="style2.css" />
  </head>
  <body>
    <canvas id="canvas"> </canvas>
    <script>
      //canvas 需要一开始就在元素内定义宽高，不然在其他地方都是拉伸canvas
      let canvas = document.getElementById("canvas");
      canvas.width = document.documentElement.clientWidth;
      canvas.height = document.documentElement.clientHeight;
      // 画线
      let ctx = canvas.getContext("2d");
      ctx.fillStyle = "black";
      ctx.strokeStyle = "none";
      let painting = false;

      var isTouchDevice = "ontouchstart" in document.documentElement;

      if (isTouchDevice) {
        canvas.ontouchmove = (e) => {
          let x = e.touches[0].clientX
          let y = e.touches[0].clientY
          ctx.beginPath();
            ctx.arc(x, y, 10, 0, 2 * Math.PI);
            ctx.stroke();
            ctx.fill();
        }
      } else {
        canvas.onmousedown = () => {
          painting = true;
        };

        canvas.onmousemove = (e) => {
          if (painting === true) {
            ctx.beginPath();
            ctx.arc(e.clientX, e.clientY, 10, 0, 2 * Math.PI);
            ctx.stroke();
            ctx.fill();
            //ctx.fillRect(e.clientX - 5, e.clientY - 5, 10, 10);
          } 
        };

        canvas.onmouseup = () => {
          painting = false;
        };
      }
    </script>
  </body>
</html>
